import React from "react";
import { Row, Col, Button, Form, Input, Radio, notification } from 'antd';
import { connect } from 'dva';
import { FormComponentProps } from "antd/lib/form/Form";
import Resource from '@/components/Resource';
import { DICT } from './enum';

interface IProps extends FormComponentProps {
  dispatch?: Function;
  children?: React.ReactNode;
  loading?: boolean;
  data?: {
    id: string;
    fireSafeDutyName: string;
    fireSafeDutyPosition: string;
    fireSafeDutyPhone: string;
    fireSafeDutyEnable: string;
    fireSafeManagerName: string;
    fireSafeManagerPosition: string;
    fireSafeManagerPhone: string;
    fireSafeManagerEnable: string;
    securityCaptainName: string;
    securityCaptainPosition: string;
    securityCaptainPhone: string;
    securityCaptainEnable: string;
    safeDutyUrl: string;
    safeManagerUrl: string;
  };
  file?: {
    url: string;
    message: string;
  };
  image?: {
    url: string;
    message: string;
  };
}


@connect(({ archives_unit, loading, upload }) => ({
  data: archives_unit.personDetail || {},
  loading: loading.effects['archives_unit/queryPersonnelDetail'],
  file: upload.fileValue || {},
  image: upload.imgValue || {},
}))
class Person extends React.PureComponent<IProps, any> {
  state = {
    value: null,
    manageValue: null,
    securityValue: null,
    fileName: null,
    fileUrl: null,
    manageFileName: null,
    manageFileUrl: null,
  }

  queryData() {
    const { dispatch, form } = this.props;
    dispatch({ type: 'archives_unit/queryPersonnelDetail' })
      .then(() => {
        const { data } = this.props;
        if (data) {
          const { id, fireSafeManagerEnable, fireSafeDutyEnable, securityCaptainEnable,
            safeDutyUrl, safeManagerUrl, ...items } = data;
          const ans = { ...items };
          const manageUrlArr = safeManagerUrl && safeManagerUrl.split('/');
          const manageFileName = Array.isArray(manageUrlArr) && manageUrlArr[manageUrlArr.length - 1]
          const fileUrlArr = safeDutyUrl && safeDutyUrl.split('/');
          const fileName = Array.isArray(fileUrlArr) && fileUrlArr[fileUrlArr.length - 1]

          this.setState({
            value: fireSafeDutyEnable,
            manageValue: fireSafeManagerEnable,
            securityValue: securityCaptainEnable,
            fileName: fileName && fileName.substr(10),
            fileUrl: safeDutyUrl,
            manageFileName: manageFileName && manageFileName.substr(10),
            manageFileUrl: safeManagerUrl,
          }, () => form.setFieldsValue(ans))

        }
      })
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'archives_unit/queryDict', payload: { keyList: DICT } })
    this.queryData();
  }

  onChange = (e) => {
    this.setState({
      value: e.target.value,
    });
  };
  onManageChange = (e) => {
    this.setState({
      manageValue: e.target.value,
    });
  };
  onSecurityChange = (e) => {
    this.setState({
      securityValue: e.target.value,
    });
  }

  uploadFile(e) {
    e.persist();
    const { dispatch } = this.props;
    const targetFile = e.target.files[0];

    dispatch({
      type: targetFile.type === 'application/pdf' ? 'upload/uploadFile' : 'upload/uploadImg',
      payload: targetFile
    }).then(() => {
      const { file, image } = this.props;
      if (targetFile.type === 'application/pdf') {
        file.message === 'success' && this.setState({ fileName: targetFile.name, fileUrl: file.url })
      } else {
        image.message === 'success' && this.setState({ fileName: targetFile.name, fileUrl: image.url })
      }
    })
  }

  uploadManageFile(e) {
    e.persist();
    const { dispatch } = this.props;
    const targetFile = e.target.files[0];

    dispatch({
      type: targetFile.type === 'application/pdf' ? 'upload/uploadFile' : 'upload/uploadImg',
      payload: targetFile
    }).then(() => {
      const { file, image } = this.props;
      if (targetFile.type === 'application/pdf') {
        file.message === 'success' && this.setState({ manageFileName: targetFile.name, manageFileUrl: file.url })
      } else {
        image.message === 'success' && this.setState({ manageFileName: targetFile.name, manageFileUrl: image.url })
      }
    })
  }

  handleSubmit = (e) => {
    e.preventDefault();
    const { form, dispatch, data } = this.props;
    const { value, manageValue, securityValue, fileUrl, manageFileUrl } = this.state;
    form.validateFields((err, values) => {
      if (!err) {

        values.fireSafeDutyEnable = value;
        values.fireSafeManagerEnable = manageValue;
        values.securityCaptainEnable = securityValue;
        values.safeDutyUrl = fileUrl;
        values.safeManagerUrl = manageFileUrl;

        data && data.id ?
          dispatch({
            type: 'archives_unit/modifyPersonnel',
            payload: values
          }).then(() => this.queryData())
          :
          dispatch({
            type: 'archives_unit/createPersonnel',
            payload: values
          }).then(() => this.queryData())
      } else {
        notification['error']({
          message: `保存失败`,
          description: '字段验证不通过',
        });
      }
    })

  }

  render() {
    const { form } = this.props;
    const { fileName, fileUrl, manageFileName, manageFileUrl } = this.state;

    const { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
    };
    const longLabelLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    };
    const radioLayout = {
      labelCol: { span: 14 },
      wrapperCol: { span: 10 },
    };
    return (
      <Form style={{ marginTop: '30px' }} onSubmit={this.handleSubmit}>
        <Row>
          <Col key={1} span={5}>
            <Form.Item
              label="消防安全责任人"
              {...longLabelLayout}
            >
              {getFieldDecorator('fireSafeDutyName', {
                rules: [{ required: false, message: '消防安全责任人' }],
              })(
                <Input placeholder="请输入" />
              )}
            </Form.Item>
          </Col>
          <Col key={2} span={4}>
            <Form.Item
              label="职务"
              {...formItemLayout}
            >
              {getFieldDecorator('fireSafeDutyPosition', {
                rules: [{ required: false, message: '职务' }],
              })(
                <Input placeholder="请输入" />
              )}
            </Form.Item>
          </Col>
          <Col key={3} span={4}>
            <Form.Item
              label="联系电话"
              {...formItemLayout}
            >
              {getFieldDecorator('fireSafeDutyPhone', {
                rules: [{ required: false, message: '联系电话' }],
              })(
                <Input placeholder="请输入" />
              )}
            </Form.Item>
          </Col>
          <Col key={4} span={6}>
            <Form.Item
              label="是否经过专门消防培训"
              {...radioLayout}
            >
              <Radio.Group onChange={this.onChange} value={this.state.value}>
                <Radio value='1'>是</Radio>
                <Radio value='0'>否</Radio>
              </Radio.Group>
            </Form.Item>
          </Col>
          <Col key={5} span={4}>
            <Form.Item>
              {fileName ?
                <Resource isImg={!fileName.includes('.pdf')} fileUrl={fileUrl} fileName={fileName} showDelBtn={true}
                  onClick={() => this.setState({ fileName: null, fileUrl: '' })} />
                :
                <>
                  <input style={{ opacity: 0, width: 150, zIndex: 10, position: 'absolute', cursor: 'pointer' }}
                    onChange={(e) => {
                      this.uploadFile(e)
                    }}
                    onClick={(event:any) => { event.target.value = null }}
                    type='file'
                  />
                  <Button type="link" icon="plus">上传消防安全责任书</Button>
                </>
              }
              <a style={{ display: 'block' }}
                href=""
                download="消防安全责任书"
              >
                <Button type="primary" style={{ marginLeft: '20px', marginTop: '-20px' }}>模板下载</Button>
              </a>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col key={1} span={5}>
            <Form.Item
              label="消防安全管理人"
              {...longLabelLayout}
            >
              {getFieldDecorator('fireSafeManagerName', {
                rules: [{ required: false, message: '消防安全管理人' }],
              })(
                <Input placeholder="请输入" />
              )}
            </Form.Item>
          </Col>
          <Col key={2} span={4}>
            <Form.Item
              label="职务"
              {...formItemLayout}
            >
              {getFieldDecorator('fireSafeManagerPosition', {
                rules: [{ required: false, message: '职务' }],
              })(
                <Input placeholder="请输入" />
              )}
            </Form.Item>
          </Col>
          <Col key={3} span={4}>
            <Form.Item
              label="联系电话"
              {...formItemLayout}
            >
              {getFieldDecorator('fireSafeManagerPhone', {
                rules: [{ required: false, message: '联系电话' }],
              })(
                <Input placeholder="请输入" />
              )}
            </Form.Item>
          </Col>
          <Col key={4} span={6}>
            <Form.Item
              label="是否经过专门消防培训"
              {...radioLayout}
            >
              <Radio.Group onChange={this.onManageChange} value={this.state.manageValue}>
                <Radio value='1'>是</Radio>
                <Radio value='0'>否</Radio>
              </Radio.Group>
            </Form.Item>
          </Col>
          <Col key={5} span={4}>
            <Form.Item>
              {manageFileName ?
                <Resource isImg={!manageFileName.includes('.pdf')} fileName={manageFileName} fileUrl={manageFileUrl} showDelBtn={true}
                  onClick={() => this.setState({ manageFileName: null, manageFileUrl: '' })} />
                :
                <>
                  <input style={{ opacity: 0, width: 150, zIndex: 10, position: 'absolute', cursor: 'pointer' }}
                    onChange={(e) => {
                      this.uploadManageFile(e)
                    }}
                    onClick={(event:any) => { event.target.value = null }}
                    type='file'
                  />
                  <Button type="link" icon="plus">上传消防安全管理人任命书</Button>
                </>}
              <a style={{ display: 'block' }}
                href=""
                download="消防安全管理人任命书"
              >
                <Button type="primary" style={{ marginLeft: '20px', marginTop: '-20px' }}>模板下载</Button>
              </a>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col key={1} span={5}>
            <Form.Item
              label="保安队长"
              {...longLabelLayout}
            >
              {getFieldDecorator('securityCaptainName', {
                rules: [{ required: false, message: '保安队长' }],
              })(
                <Input placeholder="请输入" />
              )}
            </Form.Item>
          </Col>
          <Col key={2} span={4}>
            <Form.Item
              label="职务"
              {...formItemLayout}
            >
              {getFieldDecorator('securityCaptainPosition', {
                rules: [{ required: false, message: '职务' }],
              })(
                <Input placeholder="请输入" />
              )}
            </Form.Item>
          </Col>
          <Col key={3} span={4}>
            <Form.Item
              label="联系电话"
              {...formItemLayout}
            >
              {getFieldDecorator('securityCaptainPhone', {
                rules: [{ required: false, message: '联系电话' }],
              })(
                <Input placeholder="请输入" />
              )}
            </Form.Item>
          </Col>
          <Col key={4} span={6}>
            <Form.Item
              label="是否经过专门消防培训"
              {...radioLayout}
            >
              <Radio.Group onChange={this.onSecurityChange} value={this.state.securityValue}>
                <Radio value={1}>是</Radio>
                <Radio value={0}>否</Radio>
              </Radio.Group>
            </Form.Item>
          </Col>
          <Col key={5} span={4} />
        </Row>
        <Button style={{ marginLeft: '5%', marginTop: '10%' }} type="primary" htmlType="submit">保存</Button>
      </Form>
    )
  }
}


const Persons = Form.create<IProps>()(Person);
export default Persons;